/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.api;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.request.SimpleTextRequestMessage;
import cn.easyplatform.messages.vos.SqlVo;
import cn.easyplatform.spi.service.AddonService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.ListRowVo;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.ext.ComponentHandler;
import cn.easyplatform.web.service.ServiceLocator;
import cn.easyplatform.web.task.BackendException;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.task.event.EventListenerHandler;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.task.zkex.list.PanelSupport;
import cn.easyplatform.web.utils.PageUtils;
import cn.easyplatform.web.utils.WebUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.impl.XulElement;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class DefaultDataHandler implements ComponentHandler {

    private OperableHandler main;

    private ListSupport support;

    private Component anchor;

    public DefaultDataHandler(OperableHandler mainTaskHandler) {
        this.main = mainTaskHandler;
    }

    public DefaultDataHandler(ListSupport support, Component anchor) {
        this.support = support;
        this.main = support.getMainHandler();
        this.anchor = anchor;
    }

    @Override
    public <T> List<T> selectList(Class<T> clazz, String query, Object... params) {
        return selectList(clazz, null, query, 0, 0, false, params);
    }

    @Override
    public <T> List<T> selectList0(Class<T> clazz, String dsId, String query, Object... params) {
        return selectList(clazz, dsId, query, 0, 0, false, params);
    }

    @Override
    public <T> List<T> selectList(Class<T> clazz, String query, int pageNo, int pageSize, boolean getTotalCount, Object... params) {
        return selectList(clazz, null, query, pageNo, pageSize, getTotalCount, params);
    }

    @Override
    public <T> List<T> selectList(Class<T> clazz, String dsId, String query, int pageNo, int pageSize, boolean getTotalCount, Object... params) {
        if (Strings.isBlank(query))
            return Collections.emptyList();
        AddonService ds = ServiceLocator.lookup(AddonService.class);
        SqlVo vo = new SqlVo();
        vo.setQuery(query);
        vo.setRid(dsId);
        vo.setGetTotalCount(getTotalCount);
        vo.setPageNo(pageNo);
        vo.setPageSize(pageSize);
        vo.setGetFieldName(clazz == Map.class);
        for (Object parameter : params)
            vo.setParameter(parameter);
        if (anchor != null) {
            ListRowVo rowVo = WebUtils.getAnchorValue(anchor);
            Object[] data = support.isCustom() ? rowVo.getData() : rowVo
                    .getKeys();
            vo.setId(support.getComponent().getId());
            vo.setKeys(data);
        } else if (main instanceof PanelSupport) {
            ListSupport ls = ((PanelSupport) main).getList();
            vo.setId(ls.getComponent().getId());
        }
        IResponseMessage<?> resp = ds.selectList(new SimpleRequestMessage(main.getId(), vo));
        if (resp.isSuccess())
            return (List<T>) resp.getBody();
        throw new BackendException(resp);
    }

    @Override
    public <T> T selectOne(Class<T> clazz, String query, Object... params) {
        return selectOne(clazz, null, query, params);
    }

    @Override
    public <T> T selectOne0(Class<T> clazz, String dsId, String query, Object... params) {
        if (Strings.isBlank(query))
            return null;
        AddonService ds = ServiceLocator.lookup(AddonService.class);
        SqlVo vo = new SqlVo();
        vo.setQuery(query);
        vo.setRid(dsId);
        for (Object parameter : params)
            vo.setParameter(parameter);
        if (anchor != null) {
            ListRowVo rowVo = WebUtils.getAnchorValue(anchor);
            Object[] data = support.isCustom() ? rowVo.getData() : rowVo
                    .getKeys();
            vo.setId(support.getComponent().getId());
            vo.setKeys(data);
        } else if (main instanceof PanelSupport) {
            ListSupport ls = ((PanelSupport) main).getList();
            vo.setId(ls.getComponent().getId());
        }
        IResponseMessage<?> resp = ds.selectOne(new SimpleRequestMessage(vo));
        if (resp.isSuccess())
            return (T) resp.getBody();
        throw new BackendException(resp);
    }

    @Override
    public Object selectObject(String query, Object... params) {
        return selectObject(null, query, params);
    }

    @Override
    public Object selectObject0(String dsId, String query, Object... params) {
        if (Strings.isBlank(query))
            return null;
        AddonService ds = ServiceLocator.lookup(AddonService.class);
        SqlVo vo = new SqlVo();
        vo.setQuery(query);
        vo.setRid(dsId);
        for (Object parameter : params)
            vo.setParameter(parameter);
        if (anchor != null) {
            ListRowVo rowVo = WebUtils.getAnchorValue(anchor);
            Object[] data = support.isCustom() ? rowVo.getData() : rowVo
                    .getKeys();
            vo.setId(support.getComponent().getId());
            vo.setKeys(data);
        } else if (main instanceof PanelSupport) {
            ListSupport ls = ((PanelSupport) main).getList();
            vo.setId(ls.getComponent().getId());
        }
        IResponseMessage<?> resp = ds.selectObject(new SimpleRequestMessage(main.getId(), vo));
        if (resp.isSuccess())
            return resp.getBody();
        throw new BackendException(resp);
    }

    @Override
    public int executeUpdate(String sql, Object... params) {
        return executeUpdate(null, sql, params);
    }

    @Override
    public int executeUpdate0(String dsId, String sql, Object... params) {
        if (Strings.isBlank(sql))
            return 0;
        AddonService ds = ServiceLocator.lookup(AddonService.class);
        SqlVo vo = new SqlVo();
        vo.setQuery(sql);
        vo.setRid(dsId);
        for (Object parameter : params)
            vo.setParameter(parameter);
        if (anchor != null) {
            ListRowVo rowVo = WebUtils.getAnchorValue(anchor);
            Object[] data = support.isCustom() ? rowVo.getData() : rowVo
                    .getKeys();
            vo.setId(support.getComponent().getId());
            vo.setKeys(data);
        } else if (main instanceof PanelSupport) {
            ListSupport ls = ((PanelSupport) main).getList();
            vo.setId(ls.getComponent().getId());
        }
        IResponseMessage<?> resp = ds.update(new SimpleRequestMessage(main.getId(), vo));
        if (resp.isSuccess())
            return (Integer) resp.getBody();
        return 0;
    }

    @Override
    public Object getVariable(String name) {
        AddonService ds = ServiceLocator.lookup(AddonService.class);
        IResponseMessage<?> resp = ds.getVariable(new SimpleTextRequestMessage(main.getId(), name));
        if (resp.isSuccess())
            return resp.getBody();
        throw new BackendException(resp);
    }

    @Override
    public void addEventListener(String eventName, Component comp) {
        addEventListener(eventName, comp, comp.getEvent());
    }

    @Override
    public void addEventListener(String eventName, Component comp, String content) {
        comp.addEventListener(eventName, new EventListenerHandler(eventName,
                support == null ? main : support, content, anchor));
    }

    @Override
    public void processEventHandler(Component comp) {
        PageUtils.processEventHandler(main, comp, anchor);
    }

    @Override
    public String getUserId() {
        return Contexts.getUser().getId();
    }

    @Override
    public String getOrgId() {
        return Contexts.getUser().getOrgId();
    }

    @Override
    public String getProjectId() {
        return Contexts.getEnv().getProjectId();
    }
}
